var QuerySupplyOrder = function () {
  var template = /* html */ `
    <div class="query-supply-order" v-loading.fullscreen.lock="loading">
      <search-btn-view btn-text="查询申补单" @before-open="resetSearch" @search="searchData">
        <div slot="search-content">
          <el-form inline label-width="auto" size="medium">
            <el-form-item label="订单信息" >
              <el-input class="search-input" v-model="search.orderId" placeholder="请输入订单信息"></el-input>
            </el-form-item>
            <el-form-item label="物料信息" >
              <el-input class="search-input" v-model="search.materialDetail" placeholder="请输入物料信息"></el-input>
            </el-form-item>
            <el-form-item label="审核状态" >
              <el-select clearable class="search-input" v-model="search.status" placeholder="请选择审核状态">
                <el-option v-for="status in statusList" :key="status.value" :value="status.value" :label="status.label">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </search-btn-view>
      <div class="query-order-table-div">
        <el-table fit stripe border default-expand-all :data="orderList" height="parent" row-key="id" :span-method="spanMethod"
          :row-class-name="getRowClassName">
          <el-table-column sortable label="状态" prop="status" column-key="personLiable" min-width="100px" header-align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.rowType!=='personLiable'">
                {{i18n.getMsg('materialSupplyOrder.status.'+scope.row.status)}}
              </span>
              <div v-else style="width:calc(100% - 16px)">
                <person-liable-show readonly :order="scope.row"></person-liable-show>
              </div>
            </template>
          </el-table-column>
          <el-table-column sortable label="订单编号" prop="orderId" min-width="140px" header-align="center"></el-table-column>
          <el-table-column sortable label="公司订单编号" prop="compnyOrderId" min-width="140px" header-align="center"></el-table-column>
          <el-table-column sortable label="工厂型号" prop="factoryId" min-width="140px" header-align="center"></el-table-column>
          <el-table-column sortable label="客户型号" prop="coustomId" min-width="140px" header-align="center"></el-table-column>
          <el-table-column sortable label="订单序号" prop="rowIndex" min-width="100px" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.rowIndex===-1?globalConfig.orderDefaultRowIndex:scope.row.rowIndex}}</span>
            </template>
          </el-table-column>
          <el-table-column sortable label="供应商" prop="providerName" min-width="120px" header-align="center"></el-table-column>
          <el-table-column sortable label="物料名称" prop="materialName" min-width="120px" header-align="center"></el-table-column>
          <el-table-column sortable label="物料类型" prop="materialType" min-width="100px" header-align="center"></el-table-column>
          <el-table-column sortable label="编号" prop="color" min-width="100px" header-align="center"></el-table-column>
          <el-table-column sortable label="描述" prop="colorDescription" min-width="120px" header-align="center"></el-table-column>
          <el-table-column sortable label="规格" prop="model" min-width="100px" header-align="center"></el-table-column>
          <el-table-column sortable label="单价" prop="unitPrice" min-width="100px" align="center"></el-table-column>
          <el-table-column sortable label="单位" prop="unit" min-width="100px" align="center"></el-table-column>
          <el-table-column sortable label="申补类型" prop="type" min-width="100px" align="center">
            <template slot-scope="scope">
              <span>{{i18n.getMsg('materialSupplyOrder.orderType.'+scope.row.type)}}</span>
            </template>
          </el-table-column>
          <el-table-column sortable label="申补数量" prop="applyCount" min-width="100px" align="center"></el-table-column>
          <el-table-column sortable label="申补原因" prop="applyReason" min-width="140px" header-align="center"></el-table-column>
          <el-table-column sortable label="公司占比" prop="conpanyShare" min-width="100px" align="center">
            <template slot-scope="scope" v-if="scope.row.conpanyShare!==null">
              <span>{{scope.row.conpanyShare}}%</span>
            </template>
          </el-table-column>
          <el-table-column sortable label="制单人" prop="createUser" min-width="120px" header-align="center"></el-table-column>
          <el-table-column sortable :resizable="false" label="制单日期" sort-by="createUser" width="100px" align="center">
            <template slot-scope="scope" v-if="scope.row.createTime!==''">
              <span>{{moment(scope.row.createTime).format('YYYY-MM-DD')}}</span>
            </template>
          </el-table-column>
          <el-table-column sortable label="审核人" prop="approvalUser" min-width="120px" header-align="center"></el-table-column>
          <el-table-column sortable :resizable="false" label="审核日期" sort-by="createUser" width="100px" align="center">
            <template slot-scope="scope" v-if="scope.row.approvalTime!==''">
              <span>{{moment(scope.row.approvalTime).format('YYYY-MM-DD')}}</span>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" label="操作" :width="handlerWidth" header-align="center" fixed="right">
            <template slot-scope="scope" v-if="scope.row.status!==undefined">
              <template v-if="scope.row.status===0">
                <el-button type="primary" size="mini" @click="approvalOrder(scope.row)">审核</el-button>
                <el-button type="danger" size="mini" @click="retreatOrder(scope.row)">退回</el-button>
              </template>
              <template v-if="scope.row.status!==1&&scope.row.createUserId===user.userId">
                <el-button type="primary" size="mini" @click="updateOrder(scope.row)">修改</el-button>
                <el-button type="danger" size="mini" @click="deleteOrder(scope.row)">删除</el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <table-pagination v-if="pagination.totalCount!==0" :pagination="pagination" @change="pageChange">
      </table-pagination>

      <prompt-form :title="dialogTitle" :visible.sync="openDialog" :option="orderOption" :data="selectOrder"
        @close="dialogClose" width="250px" @ensure="toHandleOrder"></prompt-form>
    </div>
  `;

  return {
    mixins: [
      supplyOrderMixin('query'),
      tablePaginationMixin()
    ],

    data: function () {
      var search = {
        orderId: '',
        materialDetail: '',
        status: ''
      };
      return {
        loading: false,
        search: _.cloneDeep(search),
        oldSearch: _.cloneDeep(search),
        orderList: [],
        statusList: i18n.getDropDown('materialSupplyOrder.status', [0, 1, 2]),
        handlerWidth: '50px',
        user: null,
        i18n: i18n,
        moment: moment,
        dialogTitle: '',
        openDialog: false,
        orderOption: null,
        selectOrder: null
      };
    },

    created: function () {
      this.loading;
      var self = this;
      SysUtil.getUser().then(function (user) {
        self.user = user;
        self.loading = false;
        self.setOrderList(true);
      }).catch(function () {
        self.loading = false;
      });
    },

    methods: {
      setOrderList: function (isSearch) {
        if (!isSearch) {
          this.search = _.cloneDeep(this.oldSearch);
        }

        var pagination = this.pagination;
        var currentPage = pagination.currentPage;
        var pageSize = pagination.pageSize;
        var start = (currentPage - 1) * pageSize;
        var postData = {
          start: start,
          length: pageSize
        };

        var search = this.search;
        var fields = ['orderId', 'materialDetail', 'status'];
        SysUtil.setPostData(postData, search, fields, false, true);

        this.loading = true;
        var self = this;
        ajaxRequest('applyRepairForm/getApplyRepairForm', postData).then(function (res) {
          if (isSearch) {
            self.oldSearch = _.cloneDeep(self.search);
          }

          var orderList = res.returnData;
          var user = self.user;
          var hasApproval = false,
            hasRetreat = false;
          for (var i = 0; i < orderList.length; i++) {
            var order = orderList[i];
            var status = order.status;
            if (status === 1) {
              var conpanyShare = order.conpanyShare;
              order.conpanyShare = Number(conpanyShare);
            } else {
              order.conpanyShare = null;
            }

            order.createTime = SysUtil.formatString2Date(order.createTime);
            order.approvalTime = SysUtil.formatString2Date(order.approvalTime);

            if (order.type === 2) {
              order.children = self.getOrderPersonLiableData(order);
            }

            if (!hasApproval && status === 0) {
              hasApproval = true;
            }
            if (!hasRetreat && status !== 1 && user.userId === order.createUserId) {
              hasRetreat = true;
            }
          }

          self.setHandlerWidth(hasApproval, hasRetreat);
          self.orderList = orderList;
          self.pagination.totalCount = res.iTotalRecords;
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      getOrderPersonLiableData: function (order) {
        var persons = order.personLiableList;
        persons = _.map(persons, function (person) {
          return {
            id: person.id,
            name: person.userId,
            share: person.share
          };
        });
        var children = [{
          id: SysUtil.getId(),
          rowType: 'personLiable',
          parentId: order.id,
          personLiableList: persons,
          conpanyShare: null,
          createTime: '',
          approvalTime: ''
        }];
        return children;
      },

      setHandlerWidth: function (hasApproval, hasRetreat) {
        var handlerWidth = 50;
        if (hasApproval && hasRetreat) {
          handlerWidth = 245;
        } else if (hasApproval || hasRetreat) {
          handlerWidth = 125;
        }
        this.handlerWidth = handlerWidth + 'px';
      },

      resetSearch: function () {
        this.search = _.cloneDeep(this.oldSearch);
      },

      searchData: function () {
        this.pagination.currentPage = 1;
        this.setOrderList(true);
      },

      pageChange:function(){
        this.setOrderList();
      },

      approvalOrder: function (order) {
        this.orderOption = {
          formItems: [{
            type: 'number',
            field: 'companyShare',
            label: '公司占比(%)',
            precision: 1,
            min: 0,
            max: 100
          }]
        };
        this.selectOrder = {
          id: order.id,
          companyShare: undefined,
          type: 'approval'
        };
        this.dialogTitle = '申补单审核';
        this.openDialog = true;
      },

      toApprovalOrder: function (order, inputData) {
        var companyShare = inputData.companyShare;
        var code = '';
        if (companyShare === undefined) {
          code = 'companyShare';
        } else if (companyShare === 0) {
          code = 'companyShareZero';
        }

        if (code !== '') {
          var msg = i18n.getMsg(`materialSupplyOrder.error.${code}`);
          this.$alert(msg, '信息');
          return;
        }

        this.loading = true;
        var self = this;
        ajaxRequest('applyRepairForm/approvalApplyRepairForm', {
          id: order.id,
          status: 1,
          conpanyShare: companyShare,
          applyType: 2
        }).then(function () {
          self.$alert('该申补单成功审核', '信息', {
            callback: function () {
              self.setOrderList();
            }
          });
          self.openDialog = false;
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      retreatOrder: function (order) {
        this.loading = true;
        var self = this;
        ajaxRequest('applyRepairForm/approvalApplyRepairForm', {
          id: order.id,
          status: 2,
          conpanyShare: 0
        }).then(function () {
          self.$alert('该申补单成功退回', '信息', {
            callback: function () {
              self.setOrderList();
            }
          });
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      updateOrder: function (order) {
        this.orderOption = {
          formItems: [{
            type: 'number',
            field: 'applyCount',
            label: '申补数量',
            precision: 2,
            min: 0
          }]
        };
        this.selectOrder = {
          id: order.id,
          applyCount: order.applyCount,
          type: 'update'
        };
        this.dialogTitle = '修改申补单';
        this.openDialog = true;
      },

      toUpdateOrder: function (order, inputData) {
        var applyCount = inputData.applyCount;
        var code = '';
        if (applyCount === undefined) {
          code = 'applyCount';
        } else if (applyCount === 0) {
          code = 'applyCountZero';
        } else if (applyCount === order.applyCount) {
          code = 'applyCountSame';
        }

        if (code !== '') {
          var msg = i18n.getMsg(`materialSupplyOrder.error.${code}`);
          this.$alert(msg, '信息');
          return;
        }

        this.loading = true;
        var self = this;
        ajaxRequest('applyRepairForm/updateApplyRepairForm', {
          id: order.id,
          applyCount: applyCount
        }).then(function () {
          self.$alert('该申补单成功修改', '信息', {
            callback: function () {
              self.setOrderList();
            }
          });
          self.openDialog = false;
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      deleteOrder: function (order) {
        this.loading = true;
        var self = this;
        ajaxRequest('applyRepairForm/deleteApplyRepairForm', {
          id: order.id
        }).then(function () {
          self.$alert('该申补单成功删除', '信息', {
            callback: function () {
              self.setOrderList();
            }
          });
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      toHandleOrder: function (inputData) {
        var selectOrder = this.selectOrder;
        var type = selectOrder.type;
        if (type === 'approval') {
          this.toApprovalOrder(selectOrder, inputData);
        } else if (type === 'update') {
          this.toUpdateOrder(selectOrder, inputData);
        }
      },

      dialogClose: function () {
        this.selectOrder = null;
        this.orderOption = null;
        this.dialogTitle = '';
      }
    },

    components: {
      SearchBtnView: SearchBtnView,
      PersonLiableShow: PersonLiableShow,
      PromptForm: PromptForm
    },

    template: template
  };
}();
